package com.ocom.webapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.ocom.common.constant.MapKey;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.payconfig.FeeDataListVo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.MqSubsidyClientService;
import com.ocom.webapi.service.FeeDataService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.hutool.poi.excel.cell.CellUtil.getCellValue;
@Service
public class FeeDataServiceImpl implements FeeDataService {
    @Resource
    RedisUtil redisUtil;
    @Resource
    MqSubsidyClientService mqSimpleService;
    @Override
    public Result feeDetaiImportData(Long comId, int feeItemId, MultipartFile file) {
        Workbook workbook = null ;
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        if(fileName.endsWith("xls")){
            //2003
            try {
                workbook = new HSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(fileName.endsWith("xlsx")){
            //2007
            try {
                workbook = new XSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
//            try {
//                throw new Exception("文件不是Excel文件");
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            return ResultUtil.error(ResultEnum.Err_400,"文件不是Excel文件");
        }
        if(workbook == null){
            return null;
        }

        assert workbook != null;
        Sheet sheet = workbook.getSheetAt(0);
        int rows = sheet.getLastRowNum();// 指的行数，一共有多少行+
        if(rows==0){
            try {
                throw new Exception("请填写数据");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Long timestamp = System.currentTimeMillis();
        Map<String,Object> map1=new HashMap<>();
        map1.put("key","ImportErr:detail:"+comId+":"+timestamp);
        map1.put("type",8);
        map1.put("name","缴费批量导入");
        map1.put("timestamp",timestamp);
        map1.put("datetime", DateUtil.getDateTime());
        redisUtil.leftPush("ImportErr:"+comId,map1,86400l);
        String errMsg = "";
        for (int i = 1; i < rows+1; i++) {
            MapKey mapKey = new MapKey();
            FeeDataListVo feeData = new FeeDataListVo();
            Map<String, Object> map = new HashMap<>();
            feeData.setComId(SecurityUtils.getYoCiUser().getComId());
//            feeData.setComId(comId);
//            voucherData.setComId(1L);
            feeData.setFeeItemId(feeItemId);
            // 读取左端单元格
            Row row = sheet.getRow(i);
            // 行不为空
            if (row != null) {
                // 人员编号
                String pCode = JSON.toJSONString(getCellValue(row.getCell(0))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pCode)){
                    feeData.setPCode(pCode); //替换pCode
                }else{
                    errMsg = "pCode学工号为空";
                }
                //姓名
                String pName = JSON.toJSONString(getCellValue(row.getCell(1))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pName) && !pName.equals("0")){
                    try{
                        feeData.setPName(pName);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    errMsg = "人员姓名为空";
                }
                String planMoney = JSON.toJSONString(getCellValue(row.getCell(2))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(planMoney)){
                    try{
                        feeData.setPlanMoney(Integer.parseInt(planMoney));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    errMsg = "计划缴费金额为空";
                }
                //调用mq
                if(CommonUtil.isNull(errMsg)){
                    mqSimpleService.importFeeDetail(feeData);
                }else{
                    Map<String,Object> errmap =new HashMap<>();
                    errmap.put("errMsg",errMsg);
                    errmap.put("json",feeData);
                    redisUtil.leftPush("ImportErr:detail:"+comId+":"+timestamp,errmap,86400l);
                }
            }
        }
        return ResultUtil.success(errMsg);
    }
}
